package com.dodo.blog.ui.page.admin;

import com.dodo.blog.model.Category;
import com.dodo.blog.model.Role;
import com.dodo.blog.server.CategoryService;
import com.dodo.blog.ui.ajax.Response;
import com.dodo.blog.ui.ajax.annotation.GetModel;
import com.dodo.blog.ui.ajax.annotation.SetModel;
import com.dodo.blog.ui.authorization.Authorized;
import com.dodo.blog.ui.component.composite.FieldSet;
import com.dodo.blog.ui.component.composite.FormRow;
import com.dodo.blog.ui.component.container.Form;
import com.dodo.blog.ui.component.input.AjaxSubmitButton;
import com.dodo.blog.ui.component.input.Anchor;
import com.dodo.blog.ui.component.input.TextBox;
import com.dodo.blog.ui.page.AbstractPage;

import javax.inject.Inject;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
@Authorized( roles = {Role.ADMIN} )
public class CategoryEdit
        extends AbstractPage
{
    private static final long serialVersionUID = 1L;

    public static final String CATEGORY_ID = "id";

    private static CategoryService categoryService;

    private static final String CATEGORY_FORM = "category-form";

    @SetModel( name = CATEGORY_FORM )
    public Response setModel( Category category )
    {
        categoryService.saveCategory( category );

        return Response.redirect( CategoryList.class );
    }

    @GetModel( name = CATEGORY_FORM )
    public Category getModel()
    {
        Long id = getLongParameter( CATEGORY_ID );

        Category category;
        if ( id != null )
        {
            category = categoryService.getCategoryById( id );
        }
        else
        {
            category = new Category();
        }

        return category;
    }

    @Override
    public void onRender()
    {
        setHeader( localize( "header.categoryEdit" ) );

        Form form = new Form( CATEGORY_FORM, Category.class );
        add( form );

        FieldSet fieldSet = new FieldSet( localize( "title.categoryEdit" ) );
        form.add( fieldSet );

        fieldSet.add( new FormRow( localize( "label.name" ), new TextBox( "name" ).setAutoFocus( true ) ) );

        form.add( new AjaxSubmitButton( "save", localize( "button.save" ) ) );
        form.add( new Anchor( "cancel", localize( "button.cancel" ), CategoryList.class ) );
    }

    @Inject
    public void setCategoryService( CategoryService categoryService )
    {
        CategoryEdit.categoryService = categoryService;
    }
}